<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Node.js," />










<meta name="description" content="目录：Node.js核心入门(一)  全局对象 常用工具 事件机制  Node.js核心入门（二）  文件系统访问 HTTP服务器与客户端文件系统 fsfs 模块是文件操作的封装，它提供了文件的读取、写入、更名、删除、遍历目录、链接等 POSIX 文件系统操作，且所有的方法都有异步和同步的形式。异步方法的最后一个参数都是一个回调函数。 传给回调函数的参数取决于具体方法，但回调函数的第一个参数都会保">
<meta name="keywords" content="Node.js">
<meta property="og:type" content="article">
<meta property="og:title" content="Node.js核心入门（二）">
<meta property="og:url" content="http://srtian96.gitee.io/blog/2018/05/06/Node.js核心入门（二）/index.html">
<meta property="og:site_name" content="Srtian&#39;Blog">
<meta property="og:description" content="目录：Node.js核心入门(一)  全局对象 常用工具 事件机制  Node.js核心入门（二）  文件系统访问 HTTP服务器与客户端文件系统 fsfs 模块是文件操作的封装，它提供了文件的读取、写入、更名、删除、遍历目录、链接等 POSIX 文件系统操作，且所有的方法都有异步和同步的形式。异步方法的最后一个参数都是一个回调函数。 传给回调函数的参数取决于具体方法，但回调函数的第一个参数都会保">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-05-14T09:18:55.245Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Node.js核心入门（二）">
<meta name="twitter:description" content="目录：Node.js核心入门(一)  全局对象 常用工具 事件机制  Node.js核心入门（二）  文件系统访问 HTTP服务器与客户端文件系统 fsfs 模块是文件操作的封装，它提供了文件的读取、写入、更名、删除、遍历目录、链接等 POSIX 文件系统操作，且所有的方法都有异步和同步的形式。异步方法的最后一个参数都是一个回调函数。 传给回调函数的参数取决于具体方法，但回调函数的第一个参数都会保">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://srtian96.gitee.io/blog/2018/05/06/Node.js核心入门（二）/"/>





  <title>Node.js核心入门（二） | Srtian'Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Srtian'Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">It's better to burn out than to fade away</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blog/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/05/06/Node.js核心入门（二）/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Node.js核心入门（二）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-05-06T12:22:54+08:00">
                2018-05-06
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Node-js/" itemprop="url" rel="index">
                    <span itemprop="name">Node.js</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  4,569
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  19
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>目录：<br><a href="https://juejin.im/entry/5ac0e2265188255c272212d4" target="_blank" rel="noopener">Node.js核心入门(一)</a></p>
<ul>
<li>全局对象</li>
<li>常用工具</li>
<li>事件机制</li>
</ul>
<p>Node.js核心入门（二）</p>
<ul>
<li>文件系统访问</li>
<li>HTTP服务器与客户端<h2 id="文件系统-fs"><a href="#文件系统-fs" class="headerlink" title="文件系统 fs"></a>文件系统 fs</h2>fs 模块是文件操作的封装，它提供了文件的读取、写入、更名、删除、遍历目录、链接等 POSIX 文件系统操作，且所有的方法都有异步和同步的形式。异步方法的最后一个参数都是一个回调函数。 传给回调函数的参数取决于具体方法，但回调函数的第一个参数都会保留给异常。 如果操作成功完成，则第一个参数会是 null 或 undefined。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>);</span><br><span class="line">fs.unlink(<span class="string">'/tmp/hello'</span>, (err) =&gt; &#123;</span><br><span class="line">  <span class="keyword">if</span> (err) <span class="keyword">throw</span> err;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'成功删除 /tmp/hello'</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>当使用同步方法时，任何异常都会被立即抛出。 可以使用 try/catch 来处理异常，或让异常向上冒泡。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>);</span><br><span class="line">fs.unlinkSync(<span class="string">'/tmp/hello'</span>);</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'成功删除 /tmp/hello'</span>);</span><br></pre></td></tr></table></figure>
<h3 id="1-fs-readFile-path-options-callback"><a href="#1-fs-readFile-path-options-callback" class="headerlink" title="1.fs.readFile(path,[options], callback)"></a>1.fs.readFile(path,[options], callback)</h3><p>fs.readFile(path,[options], callback) 是最简单的读取。它接受一个必选参数filename，表示要读取的文件名。第二个参数options是可选的，表示文件的字符编码。 callback 是回调函数，用于接收文件的内容。如果不指定 options ，则  callback 就是第二个参数。回调函数提供两个参数  err 和  data ， err 表示有没有错误发生，data 是文件内容。如果指定了  options， data 是一个解析后的字符串，否则  data 将会是以  Buffer形式表示的二进制数据。例如：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">fs.readFile(<span class="string">'/etc/passwd'</span>, <span class="string">'utf8'</span>, callback);</span><br></pre></td></tr></table></figure>
<p>需要注意的是，当 path 是一个目录时，fs.readFile() 与 fs.readFileSync() 的行为与平台有关。在 macOS、Linux 与 Windows 上，会返回一个错误。在 FreeBSD 上，会返回目录内容的表示。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 在 macOS、Linux 与 Windows 上：</span></span><br><span class="line">fs.readFile(<span class="string">'&lt;directory&gt;'</span>, (err, data) =&gt; &#123;</span><br><span class="line">  <span class="comment">// =&gt; [Error: EISDIR: illegal operation on a directory, read &lt;directory&gt;]</span></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">//  在 FreeBSD 上：</span></span><br><span class="line">fs.readFile(<span class="string">'&lt;directory&gt;'</span>, (err, data) =&gt; &#123;</span><br><span class="line">  <span class="comment">// =&gt; null, &lt;data&gt;</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h3 id="2-fs-readFileSync-path-options"><a href="#2-fs-readFileSync-path-options" class="headerlink" title="2.fs.readFileSync(path[, options])"></a>2.fs.readFileSync(path[, options])</h3><p>fs.readFileSync(filename, [encoding]) 是  fs.readFile 同步的版本。它接受的参数和  fs.readFile 相同，但读取到的文件内容会以函数返回值的形式返回。如果有错<br>误发生， fs 将会抛出异常，这时候我们就需要使用  try 和  catch 捕捉并处理异常。</p>
<h3 id="3-fs-open-path-flags-mode-callback"><a href="#3-fs-open-path-flags-mode-callback" class="headerlink" title="3.fs.open(path, flags[, mode], callback)"></a>3.fs.open(path, flags[, mode], callback)</h3><p>fs.open(path, flags[, mode], callback)是 POSIX  open 函数的<br>封装，与 C 语言标准库中的  fopen 函数类似。它接受两个必选参数， path 为文件的路径，<br>而flags 可以是以下值：</p>
<pre><code>&apos;r&apos; - 以读取模式打开文件。如果文件不存在则发生异常。

&apos;r+&apos; - 以读写模式打开文件。如果文件不存在则发生异常。

&apos;rs+&apos; - 以同步读写模式打开文件。命令操作系统绕过本地文件系统缓存。

（这对 NFS 挂载模式下打开文件很有用，因为它可以让你跳过潜在的旧本地缓存。 它对 I/O 的性能有明显的影响，所以除非需要，否则不要使用此标志。

注意，这不会使 fs.open() 进入同步阻塞调用。 如果那是你想要的，则应该使用 fs.openSync()。）

&apos;w&apos; - 以写入模式打开文件。文件会被创建（如果文件不存在）或截断（如果文件存在）。

&apos;wx&apos; - 类似 &apos;w&apos;，但如果 path 存在，则失败。

&apos;w+&apos; - 以读写模式打开文件。文件会被创建（如果文件不存在）或截断（如果文件存在）。

&apos;wx+&apos; - 类似 &apos;w+&apos;，但如果 path 存在，则失败。

&apos;a&apos; - 以追加模式打开文件。如果文件不存在，则会被创建。

&apos;ax&apos; - 类似于 &apos;a&apos;，但如果 path 存在，则失败。

&apos;a+&apos; - 以读取和追加模式打开文件。如果文件不存在，则会被创建。

&apos;ax+&apos; - 类似于 &apos;a+&apos;，但如果 path 存在，则失败。
</code></pre><p>mode 可设置文件模式（权限和 sticky 位），但只有当文件被创建时才有效。默认为 0o666，可读写。</p>
<h3 id="4-fs-read-fd-buffer-offset-length-position-callback"><a href="#4-fs-read-fd-buffer-offset-length-position-callback" class="headerlink" title="4.fs.read(fd, buffer, offset, length, position, callback)"></a>4.fs.read(fd, buffer, offset, length, position, callback)</h3><p>fs.read(fd, buffer, offset, length, position, callback) 是 POSIX  read 函数的封装，相比  fs.readFile 提供了更底层的接口。从 fd 指定的文件中读取数据。buffer 是数据将被写入到的 buffer。offset 是 buffer 中开始写入的偏移量。length是一个整数，指定要读取的字节数。position指定从文件中开始读取的位置。如果position为null，则数据从当前文件读取位置开始读取，且文件读取位置会被更新。 如果 position 为一个整数，则文件读取位置保持不变。回调有三个参数 (err, bytesRead, buffer)。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>);</span><br><span class="line">fs.open(<span class="string">'content.txt'</span>, <span class="string">'r'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">err, fd</span>) </span>&#123;</span><br><span class="line"><span class="keyword">if</span> (err) &#123;</span><br><span class="line"><span class="built_in">console</span>.error(err);</span><br><span class="line"><span class="keyword">return</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> buf = <span class="keyword">new</span> Buffer(<span class="number">8</span>);</span><br><span class="line">fs.read(fd, buf, <span class="number">0</span>, <span class="number">8</span>, <span class="literal">null</span>, <span class="function"><span class="keyword">function</span>(<span class="params">err, bytesRead, buffer</span>) </span>&#123;</span><br><span class="line"><span class="keyword">if</span> (err) &#123;</span><br><span class="line"><span class="built_in">console</span>.error(err);</span><br><span class="line"><span class="keyword">return</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'bytesRead: '</span> + bytesRead);</span><br><span class="line"><span class="built_in">console</span>.log(buffer);</span><br><span class="line">&#125;)</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>输出：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">bytesRead: <span class="number">8</span></span><br><span class="line">&lt;Buffer <span class="number">54</span> <span class="number">65</span> <span class="number">78</span> <span class="number">74</span> <span class="number">20</span> e6 <span class="number">96</span> <span class="number">87</span>&gt;</span><br></pre></td></tr></table></figure>
<h2 id="HTTP服务器与客户端"><a href="#HTTP服务器与客户端" class="headerlink" title="HTTP服务器与客户端"></a>HTTP服务器与客户端</h2><p>Node.js 标准库提供了http模块，其中封装了一个高效的 HTTP 服务器和一个简易的HTTP 客户端。 http.Server 是一个基于事件的 HTTP 服务器，它的核心由 Node.js 下层 C++<br>部分实现，而接口由 JavaScript 封装，兼顾了高性能与简易性。 http.request则是一个HTTP 客户端工具，用于向 HTTP 服务器发起请求，例如实现 Pingback或者内容抓取。</p>
<p>Node.js 中的HTTP接口被设计成支持协议的许多特性。比如，大块编码的消息。这些接口不缓冲完整的请求或响应，用户能够以流的形式处理数据。HTTP消息头由一个对象表示，其中键名是小写的，键值不能修改：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&#123; <span class="string">'content-length'</span>: <span class="string">'123'</span>,</span><br><span class="line">  <span class="string">'content-type'</span>: <span class="string">'text/plain'</span>,</span><br><span class="line">  <span class="string">'connection'</span>: <span class="string">'keep-alive'</span>,</span><br><span class="line">  <span class="string">'host'</span>: <span class="string">'mysite.com'</span>,</span><br><span class="line">  <span class="string">'accept'</span>: <span class="string">'*/*'</span> &#125;</span><br></pre></td></tr></table></figure></p>
<p>为了支持各种可能的 HTTP 应用，Node.js的 HTTP API是非常底层的。它只涉及流处理与消息解析。它把一个消息解析成消息头和消息主体，但不解析具体的消息头或消息主体。键名是小写的，键值不能修改。为了支持各种可能的 HTTP 应用，Node.js 的 HTTP API 是非常底层的。 它只涉及流处理与消息解析。 它把一个消息解析成消息头和消息主体，但不解析具体的消息头或消息主体。</p>
<h3 id="HTTP服务器"><a href="#HTTP服务器" class="headerlink" title="HTTP服务器"></a>HTTP服务器</h3><p>http.Server 是  http  模块中的 HTTP 服务器对象，用 Node.js 做的所有基于 HTTP 协议的系统，如网站、社交应用甚至代理服务器，都是基于http.Server实现的。它提供了一套封装级别很低的API，仅仅是流控制和简单的学习解析，而所有的高级功能都是通过它的接口来实现的。比如官网上的这个例子：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> http = <span class="built_in">require</span>(<span class="string">'http'</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> hostname = <span class="string">'127.0.0.1'</span>;</span><br><span class="line"><span class="keyword">const</span> port = <span class="number">3000</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> server = http.createServer(<span class="function">(<span class="params">req, res</span>) =&gt;</span> &#123;</span><br><span class="line">  res.statusCode = <span class="number">200</span>;</span><br><span class="line">  res.setHeader(<span class="string">'Content-Type'</span>, <span class="string">'text/plain'</span>);</span><br><span class="line">  res.end(<span class="string">'Hello World\n'</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">server.listen(port, hostname, () =&gt; &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`Server running at http://<span class="subst">$&#123;hostname&#125;</span>:<span class="subst">$&#123;port&#125;</span>/`</span>);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>在这段代码中，就使用了http.createServer([requestListener])来新建一个的 http.Server 实例。现在就先让我们来看看http.createServer([requestListener])吧。</p>
<h4 id="1-http-Server-的事件"><a href="#1-http-Server-的事件" class="headerlink" title="1. http.Server 的事件"></a>1. http.Server 的事件</h4><p>http.Server 是一个基于事件的 HTTP 服务器，所有的请求都被封装为独立的事件，开发者只需要对它的事件编写响应函数即可实现 HTTP 服务器的所有功能。它继承自<br>EventEmitter ，提供了以下几个事件：</p>
<ul>
<li>request：每次接收到一个请求时触发。 注意，每个连接可能有多个请求（在 HTTP keep-alive 连接的情况下）。</li>
<li>connection ：当一个新的 TCP 流被建立时触发。socket 是一个 net.Socket 类型的对象。 通常用户无需访问该事件。 注意，因为协议解析器绑定到 socket 的方式，socket 不会触发 ‘readable’ 事件。socket 也可以通过 request.connection 访问。</li>
<li>connect：每当客户端发送 HTTP CONNECT 请求时触发。 如果该事件未被监听，则发送 CONNECT 请求的客户端会关闭连接。当该事件被触发后，请求的 socket 上没有 ‘data’ 事件监听器，这意味着需要绑定 ‘data’ 事件监听器，用来处理 socket 上被发送到服务器的数据。</li>
<li>close：当服务器关闭时，该事件被触发。注意不是在用户连接断开时，而是服务器关闭时。</li>
</ul>
<p>在这些事件最常用的是request是最常用的，因此  http 提供了一个捷径：<br>http.createServer([requestListener]) ，功能是创建一个 HTTP 服务器并将requestListener 作为  request 事件的监听函数。我们上面那个官网的例子就是如此，其实它显式的实现方法是这样的：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//httpserver.js</span></span><br><span class="line"><span class="keyword">const</span> http = <span class="built_in">require</span>(<span class="string">'http'</span>);</span><br><span class="line"><span class="keyword">const</span> hostname = <span class="string">'127.0.0.1'</span>;</span><br><span class="line"><span class="keyword">const</span> port = <span class="number">3000</span>;</span><br><span class="line"><span class="keyword">const</span> server = <span class="keyword">new</span> http.Server();</span><br><span class="line">server.on(<span class="string">'request'</span>, (req, res) =&gt; &#123;</span><br><span class="line">  res.statusCode = <span class="number">200</span>;</span><br><span class="line">  res.setHeader(<span class="string">'Content-Type'</span>, <span class="string">'text/plain'</span>);</span><br><span class="line">  res.end(<span class="string">'Hello World\n'</span>);</span><br><span class="line">&#125;);</span><br><span class="line">server.listen(port, hostname, () =&gt; &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`Server running at http://<span class="subst">$&#123;hostname&#125;</span>:<span class="subst">$&#123;port&#125;</span>/`</span>);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h4 id="2-http-ServerRequest"><a href="#2-http-ServerRequest" class="headerlink" title="2. http.ServerRequest"></a>2. http.ServerRequest</h4><p>http.ServerRequest  是 HTTP 请求的信息，是后端开发者最关注的内容。它一般由http.Server 的 request 事件发送，作为第一个参数传递，通常简称  request 或 HTTP 请求一般可以分为两部分：请求头（Request Header）和请求体（Requset Body）。以上内容由于长度较短都可以在请求头解析完成后立即读取。而请求体可能相对较长，需要一定的时间传输，因此  http.ServerRequest  提供了以下3个事件用于控制请求体传输。req。HTTP请求一般可以分为两部分：请求头（RequestHeader）和请求体（RequsetBody）。以上内容由于长度较短都可以在请求头解析完成后立即读取。而请求体可能相对较长，需要一定的时间传输，因此http.ServerRequest提供了以下3个事件用于控制请求体传输。http.ServerRequest提供了3个事件用于控制请求体传输：</p>
<ol>
<li>data：当请求体数据到来时，该事件被触发，提供一个参数给回调函数，是接受到的数据，该事件可能被多次调用（所有data按顺序的集合，是请求体数据）。如果该事件没有被监听，请求体将被抛弃；</li>
<li>end：当请求体数据完成时该事件触发。此后不再触发data事件；</li>
<li><p>close：用户当前请求结束时，该事件被触发。不同于end，如果用户强制终止了传输，也还是调用close。</p>
<pre><code>         表4-2  ServerRequest 的属性
名 称                  含 义
complete        客户端请求是否已经发送完成
httpVersion     HTTP 协议版本，通常是 1.0 或 1.1
method          HTTP 请求方法，如 GET、POST、PUT、DELETE 等
url             原始的请求路径，例如 /static/image/x.jpg 或 /user?name=byvoid
headers         HTTP 请求头
trailers        HTTP 请求尾（不常见）
connection      当前 HTTP 连接套接字，为 net.Socket 的实例
socket          connection 属性的别名
client          client 属性的别名
</code></pre><h4 id="3-获取-GET-请求内容"><a href="#3-获取-GET-请求内容" class="headerlink" title="3. 获取 GET 请求内容"></a>3. 获取 GET 请求内容</h4><p>注意， http.ServerRequest 提供的属性中没有类似于 PHP 语言中的 $_GET 或 $_POST 的属性，GET请求被直接内嵌在路径中。URL是完整的请求路径（包括？后面的部分），因此手动解析后面的内容作为GET请求的参数。Node.js的url模块中的parse函数提供了这个功能。</p>
</li>
</ol>
<p>以url：<a href="http://127.0.0.1/user?name=byvoid&amp;email=byvoid@byvoid.com为例：" target="_blank" rel="noopener">http://127.0.0.1/user?name=byvoid&amp;email=byvoid@byvoid.com为例：</a></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> http = <span class="built_in">require</span>(<span class="string">"http"</span>);</span><br><span class="line"><span class="keyword">var</span> url = <span class="built_in">require</span>(<span class="string">"url"</span>);</span><br><span class="line"><span class="keyword">var</span> server = <span class="keyword">new</span> http.Server();</span><br><span class="line">server.on(<span class="string">"request"</span>, <span class="function"><span class="keyword">function</span> (<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (req.url == <span class="string">"/favicon.ico"</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">var</span> m = url.parse(req.url, <span class="literal">true</span>);</span><br><span class="line">    <span class="built_in">console</span>.log(m)</span><br><span class="line">    res.writeHead(<span class="number">200</span>, &#123;<span class="string">'Content-type'</span>: <span class="string">'text/html;charset = utf8'</span>&#125;);</span><br><span class="line">    res.end();</span><br><span class="line">&#125;)</span><br><span class="line">server.listen(<span class="number">80</span>);</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">"The server begin"</span>);</span><br></pre></td></tr></table></figure>
<p>console.log输出内容：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">Url &#123;</span><br><span class="line">  protocol: <span class="literal">null</span>,</span><br><span class="line">  slashes: <span class="literal">null</span>,</span><br><span class="line">  auth: <span class="literal">null</span>,</span><br><span class="line">  host: <span class="literal">null</span>,</span><br><span class="line">  port: <span class="literal">null</span>,</span><br><span class="line">  hostname: <span class="literal">null</span>,</span><br><span class="line">  hash: <span class="literal">null</span>,</span><br><span class="line">  search:<span class="string">'?name=byvoid&amp;email=byvoid@byvoid.com'</span>,</span><br><span class="line">  query: &#123; <span class="attr">name</span>: <span class="string">'byvoid'</span>, <span class="attr">email</span>:<span class="string">'byvoid@byvoid.com'</span> &#125;,</span><br><span class="line">  pathname: <span class="string">'/user'</span>,</span><br><span class="line">  path:<span class="string">'/user?name=byvoid&amp;email=byvoid@byvoid.com'</span>,</span><br><span class="line">  href:<span class="string">'/user?name=byvoid&amp;email=byvoid@byvoid.com'</span> </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h4 id="4-获取-POST-请求内容"><a href="#4-获取-POST-请求内容" class="headerlink" title="4. 获取 POST 请求内容"></a>4. 获取 POST 请求内容</h4><p>HTTP 协议1.1版本提供了8种标准的请求方法，而其中最常见的就是 GET 和 POST。相比GET请求把所有的内容编码到访问路径中，POST 请求的内容全部都在请求体中。http.ServerRequest 并没有一个属性内容是在请求体中，原因是等待请求体传输可能是一件耗时的工作，譬如上传文件。而很多时候我们可能并不需要理会请求体的内容，且恶意的 POST<br>请求会大大消耗服务器的资源。所以 Node.js 默认是不会解析请求体的，因此当我们需要的时候，我们就要手写一个，具体实现方法如下：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> http = <span class="built_in">require</span>(<span class="string">'http'</span>);</span><br><span class="line"><span class="keyword">var</span> querystring = <span class="built_in">require</span>(<span class="string">'querystring'</span>);</span><br><span class="line"><span class="keyword">var</span> util = <span class="built_in">require</span>(<span class="string">'util'</span>);</span><br><span class="line">http.createServer(<span class="function"><span class="keyword">function</span>(<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> post = <span class="string">''</span>;</span><br><span class="line">    req.on(<span class="string">'data'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">chunk</span>) </span>&#123;</span><br><span class="line">    post += chunk;</span><br><span class="line">&#125;);</span><br><span class="line">req.on(<span class="string">'end'</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    post = querystring.parse(post);</span><br><span class="line">    res.end(util.inspect(post));</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;).listen(<span class="number">3000</span>);</span><br></pre></td></tr></table></figure></p>
<h4 id="5-http-ServerResponse"><a href="#5-http-ServerResponse" class="headerlink" title="5.http.ServerResponse"></a>5.http.ServerResponse</h4><p>http.ServerResponse  是返回给客户端的信息，决定了用户最终能看到的结果。它也是由  http.Server 的  request  事件发送的，作为第二个参数传递，一般简称为<br>response 或 res 。http.ServerResponse 有三个重要的成员函数，用于返回响应头、响应内容以及结束请求：</p>
<ul>
<li>response.writeHead(statusCode, [headers]) ：向请求的客户端发送响应头。statusCode是HTTP状态码，如200（请求成功）、404（未找到）等。headers是一个类似关联数组的对象，表示响应头的每个属性。该函数在一个请求内最多只能调用一次，如果不调用，则会自动生成一个响应头。</li>
<li>response.write(data, [encoding]) ：向请求的客户端发送响应内容。 data 是一个  Buffer 或字符串，表示要发送的内容。如果  data 是字符串，那么需要指定<br>encoding 来说明它的编码方式，默认是 utf-8 。在 response.end 调用之前，response.write  可以被多次调用。</li>
<li>response.end([data], [encoding]) ：结束响应，告知客户端所有发送已经完成。当所有要返回的内容发送完毕的时候，该函数 必须 被调用一次。它接受两个可选参数，意义和 response.write  相同。如果不调用该函数，客户端将永远处于等待状态。</li>
</ul>
<h3 id="HTTP-客户端"><a href="#HTTP-客户端" class="headerlink" title="HTTP 客户端"></a>HTTP 客户端</h3><p>http 模块提供了两个函数 http.request和http.get，功能是作为客户端向HTTP服务器发起请求。</p>
<h4 id="1-http-request-options-callback"><a href="#1-http-request-options-callback" class="headerlink" title="1.http.request(options,callback)"></a>1.http.request(options,callback)</h4><p>http.request(options,callback)发起HTTP请求，它接受两个参数，option是一个类似关联数组的对象，表示请求的参数，callback是请求的回调函数。option常用的参数如下所示：</p>
<ul>
<li>host ：请求网站的域名或 IP 地址。</li>
<li>port ：请求网站的端口，默认 80。</li>
<li>method ：请求方法，默认是 GET。</li>
<li>path ：请求的相对于根的路径，默认是“ / ”。 QueryString  应该包含在其中。例如  /search?query=byvoid 。</li>
<li>headers ：一个关联数组对象，为请求头的内容。</li>
</ul>
<p>而callback 则传递一个参数，为 http.ClientResponse 的实例。http.request 返回一个http.ClientRequest 的实例，下面是一个通过 http.request  发送 POST 请求的代码：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> http = <span class="built_in">require</span>(<span class="string">'http'</span>);</span><br><span class="line"><span class="keyword">var</span> querystring = <span class="built_in">require</span>(<span class="string">'querystring'</span>);</span><br><span class="line"><span class="keyword">var</span> contents = querystring.stringify(&#123;</span><br><span class="line">    name: <span class="string">'byvoid'</span>,</span><br><span class="line">    email: <span class="string">'byvoid@byvoid.com'</span>,</span><br><span class="line">    address: <span class="string">'Zijing 2#, Tsinghua University'</span>,</span><br><span class="line">&#125;);</span><br><span class="line"><span class="keyword">var</span> options = &#123;</span><br><span class="line">    host: <span class="string">'www.byvoid.com'</span>,</span><br><span class="line">    path: <span class="string">'/application/node/post.php'</span>,</span><br><span class="line">    method: <span class="string">'POST'</span>,</span><br><span class="line">    headers: &#123;</span><br><span class="line">        <span class="string">'Content-Type'</span>: <span class="string">'application/x-www-form-urlencoded'</span>,</span><br><span class="line">        <span class="string">'Content-Length'</span> : contents.length</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">var</span> req = http.request(options, <span class="function"><span class="keyword">function</span>(<span class="params">res</span>) </span>&#123;</span><br><span class="line">    res.setEncoding(<span class="string">'utf8'</span>);</span><br><span class="line">    res.on(<span class="string">'data'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">data</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(data);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;);</span><br><span class="line">req.write(contents);</span><br><span class="line">req.end();</span><br></pre></td></tr></table></figure>
<p>运行结果如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">array(<span class="number">3</span>) &#123;</span><br><span class="line">[<span class="string">"name"</span>]=&gt;</span><br><span class="line">string(<span class="number">6</span>) <span class="string">"byvoid"</span></span><br><span class="line">[<span class="string">"email"</span>]=&gt;</span><br><span class="line">string(<span class="number">17</span>) <span class="string">"byvoid@byvoid.com"</span></span><br><span class="line">[<span class="string">"address"</span>]=&gt;</span><br><span class="line">string(<span class="number">30</span>) <span class="string">"Zijing 2#, Tsinghua University"</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="2-http-get-options-callback"><a href="#2-http-get-options-callback" class="headerlink" title="2.http.get(options, callback)"></a>2.http.get(options, callback)</h4><p>http 模块还提供了一个更加简便的方法用于处理GET请求：http.get(options, callback)。它是http.request的简化版，唯一的区别在于http.get自动将请求方法设为了 GET 请求，同时不需要手动调用 req.end() ：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> http = <span class="built_in">require</span>(<span class="string">'http'</span>);</span><br><span class="line">http.get(&#123;<span class="attr">host</span>: <span class="string">'www.byvoid.com'</span>&#125;, <span class="function"><span class="keyword">function</span>(<span class="params">res</span>) </span>&#123;</span><br><span class="line">    res.setEncoding(<span class="string">'utf8'</span>);</span><br><span class="line">    res.on(<span class="string">'data'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">data</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(data);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h4 id="http-ClientRequest"><a href="#http-ClientRequest" class="headerlink" title="http.ClientRequest"></a>http.ClientRequest</h4><p>该对象在 http.request() 内部被创建并返回。它表示着一个正在处理的请求，其请求头已进入队列。它提供一个response事件，即http.request或http.get第二个参数指定的回调函数的绑定对象。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> http = <span class="built_in">require</span>(<span class="string">'http'</span>);</span><br><span class="line"><span class="keyword">var</span> req = http.get(&#123;<span class="attr">host</span>: <span class="string">'www.byvoid.com'</span>&#125;);</span><br><span class="line">    req.on(<span class="string">'response'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">res</span>) </span>&#123;</span><br><span class="line">    res.setEncoding(<span class="string">'utf8'</span>);</span><br><span class="line">    res.on(<span class="string">'data'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">data</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(data);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>http.ClientRequest像http.ServerResponse一样也提供了  write 和 end 函数，用于向服务器发送请求体，通常用于 POST、PUT 等操作。所有写结束以后必须调用 end<br>函数以通知服务器，否则请求无效。http.ClientRequest  还提供了以下常用的函数:</p>
<ul>
<li>request.abort() ：标记请求为终止。 调用该方法将使响应中剩余的数据被丢弃且 socket 被销毁。</li>
<li>request.setTimeout(timeout,[callback])：设置请求超时时间， timeout为毫秒数。一旦socket被分配给请求且已连接，socket.setTimeout() 会被调用。</li>
<li>request.end([data[, encoding]][, callback])结束发送请求。如果部分请求主体还未被发送，则会刷新它们到流中。 如果请求是分块的，则会发送终止字符 ‘0\r\n\r\n’。</li>
</ul>
<h4 id="http-ClientResponse"><a href="#http-ClientResponse" class="headerlink" title="http.ClientResponse"></a>http.ClientResponse</h4><p>http.ClientResponse 与  http.ServerRequest 相似，提供了三个事件 data 、end和 close，分别在数据到达、传输结束和连接结束时触发，其中  data 事件传递一个参数chunk ，表示接收到的数据。</p>
<p>http.ClientResponse  也提供了一些属性，用于表示请求的结果状态：</p>
<pre><code>statusCode   HTTP 状态码，如 200、404、500
httpVersion  HTTP 协议版本，通常是 1.0 或 1.1
headers      HTTP 请求头
trailers     HTTP 请求尾（不常见）
</code></pre><p>http.ClientResponse 还提供了以下几个特殊的函数：</p>
<ul>
<li>response.setEncoding([encoding]) ：设置默认的编码，当  data 事件被触发时，数据将会以encoding编码。默认值是null，即不编码，以  Buffer 的形式存储。常用编码为 utf8。</li>
<li>response.pause()：暂停接收数据和发送事件，方便实现下载功能。</li>
<li>response.resume() ：从暂停的状态中恢复。</li>
</ul>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/Node-js/" rel="tag"># Node.js</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/05/06/JavaScript异步编程基础/" rel="next" title="JavaScript异步编程基础">
                <i class="fa fa-chevron-left"></i> JavaScript异步编程基础
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/05/06/Node.js核心入门（一）/" rel="prev" title="Node.js核心入门（一）">
                Node.js核心入门（一） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpg"
                alt="Srtian" />
            
              <p class="site-author-name" itemprop="name">Srtian</p>
              <p class="site-description motion-element" itemprop="description">JUST DO IT.</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">59</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">37</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/srtian96" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="shenruotian@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#文件系统-fs"><span class="nav-number">1.</span> <span class="nav-text">文件系统 fs</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-fs-readFile-path-options-callback"><span class="nav-number">1.1.</span> <span class="nav-text">1.fs.readFile(path,[options], callback)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-fs-readFileSync-path-options"><span class="nav-number">1.2.</span> <span class="nav-text">2.fs.readFileSync(path[, options])</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-fs-open-path-flags-mode-callback"><span class="nav-number">1.3.</span> <span class="nav-text">3.fs.open(path, flags[, mode], callback)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-fs-read-fd-buffer-offset-length-position-callback"><span class="nav-number">1.4.</span> <span class="nav-text">4.fs.read(fd, buffer, offset, length, position, callback)</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#HTTP服务器与客户端"><span class="nav-number">2.</span> <span class="nav-text">HTTP服务器与客户端</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#HTTP服务器"><span class="nav-number">2.1.</span> <span class="nav-text">HTTP服务器</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-http-Server-的事件"><span class="nav-number">2.1.1.</span> <span class="nav-text">1. http.Server 的事件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-http-ServerRequest"><span class="nav-number">2.1.2.</span> <span class="nav-text">2. http.ServerRequest</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-获取-GET-请求内容"><span class="nav-number">2.1.3.</span> <span class="nav-text">3. 获取 GET 请求内容</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-获取-POST-请求内容"><span class="nav-number">2.1.4.</span> <span class="nav-text">4. 获取 POST 请求内容</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-http-ServerResponse"><span class="nav-number">2.1.5.</span> <span class="nav-text">5.http.ServerResponse</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#HTTP-客户端"><span class="nav-number">2.2.</span> <span class="nav-text">HTTP 客户端</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-http-request-options-callback"><span class="nav-number">2.2.1.</span> <span class="nav-text">1.http.request(options,callback)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-http-get-options-callback"><span class="nav-number">2.2.2.</span> <span class="nav-text">2.http.get(options, callback)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#http-ClientRequest"><span class="nav-number">2.2.3.</span> <span class="nav-text">http.ClientRequest</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#http-ClientResponse"><span class="nav-number">2.2.4.</span> <span class="nav-text">http.ClientResponse</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Srtian</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js">
</script>
  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">102.8k</span>
  
</div>





        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
